<?php
/*
+------------------------------------------------------------------------------+
| Copyright (c) 2008, COPEO                                          |
| All rights reserved.                                                         |
|                                                                              |
| Redistribution and use in source and binary forms, with or without           |
| modification, are permitted provided that the following conditions are met:  |
|     * Redistributions of source code must retain the above copyright         |
|       notice, this list of conditions and the following disclaimer.          |
|     * Redistributions in binary form must reproduce the above copyright      |
|       notice, this list of conditions and the following disclaimer in the    |
|       documentation and/or other materials provided with the distribution.   |
|     * Neither the name of the <organization> nor the                         |
|       names of its contributors may be used to endorse or promote products   |
|       derived from this software without specific prior written permission.  |
|                                                                              |
| THIS SOFTWARE IS PROVIDED BY draftrack team ''AS IS'' AND ANY                |
| EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED    |
| WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE       |
| DISCLAIMED. IN NO EVENT SHALL draftrack team BE LIABLE FOR ANY               |
| DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES   |
| (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND  |
| ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
| (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS|
| SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                 |
+------------------------------------------------------------------------------+
*/
/*
* Front end plugin extension to manage application initialization
*/
require_once('Zend/Controller/Plugin/Abstract.php');

/**
 * Plugin d'initialisation
 * 
 * @uses Zend_Controller_Plugin_Abstract
 */
class Myzen_Initializer extends Zend_Controller_Plugin_Abstract
{

  


    
  /**
   * Constructeur
   *
   * @param  string $env 
   * @param  string|null $root 
   * @param  string|null $ap_root 
   * @return void
  **/
	public function __construct()
	{
  		
  		//First thing is to launch the timer
  		/*
		require_once('src/Zend_extension/Log/ExecutionTime.php');
		Zend_ExecutionTime::getInstance();
  		//Magic quotes is bad functionality, each piece of software is responsible for managing inputs
  		set_magic_quotes_runtime(0);
		*/
    	// configuration initialization
    	$this->_initConfig();
    	

	}
	
  /**
   * Interruption avant le début du routage de la requête
   * A lire : http://framework.zend.com/manual/fr/zend.controller.plugins.html
   * 
   * @param  Zend_Controller_Request_Abstract $request
   * @return void
   */
  public function routeStartup(Zend_Controller_Request_Abstract $request)
  {
    // initialization methods for everything usefull
//    $this->_initLog();			// Initialization of the log writers
//    $this->_initLayout();		// Initialization of the layout handling
//    $this->_initDb();           // Initialization of the databases
//    $this->_initSession();      // Initialization of the session handling

  }
  
 
	public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {

/*

		Zend_Registry::get('dt_log')->log('Entering frontEnd dispatchLoopStartup',7);
		//Before redirecting the customer we check if the user is logged
  		$dt_AppConfig = Zend_Registry::get('dt_AppConfig');
		$dt_databases = Zend_Registry::get('dt_databases');
  		
  		// Save a reference to the Singleton instance of Zend_Auth
		$dt_auth = Zend_Auth::getInstance();
		require_once 'src/Zend_extension/Auth/Adapter/DrafTrack.php';
		//We select the database that should be used to access authentication data
		$dt_authDb =  $dt_databases->selectDb('auth');
		
		// Configure the instance with constructor parameters...
		$dt_authAdapter = new Zend_Auth_Adapter_DrafTrack($dt_authDb,$dt_AppConfig->auth);
		//we save it in the registry
		Zend_Registry::set('dt_authAdapter', $dt_authAdapter);
		
		//We first check if an identity is already stored

		if ($dt_auth->hasIdentity()) {
			Zend_Registry::get('dt_log')->log('user already identified, saving identity in dt_user',7);
    		// Identity exists; get it
    		require_once('src/Zend_extension/Auth/User.php');
    		$dt_user = $dt_auth->getIdentity();
    		Zend_Registry::set('dt_user', $dt_user);
    		
    		//If the data of the user are not compte we tell him too go complete them
    		$view = Zend_Layout::getMvcInstance()->getView();
    		if(!$dt_user->isContactDetailsComplete() && $request->getControllerName() != 'user' && $request->getActionName() != 'settings') {
 			   	$view->messagedisplay()->setMessage('Veuillez vous rendre sur <a href="'.$view->baseURL().'/user/settings/">la page des paramètres de l\'utilisateur</a> pour remplir les détails de contact','warning');
    		}
    		
		}

		//if the user is not already identified, we check if we can identify him/her
		else {
		// Attempt authentication, saving the result
		$result = $dt_auth->authenticate($dt_authAdapter);

		switch ($result->getCode()) {
		//just interested in success cases, else it is up to the controller to check that the user is Identified
    	case Zend_Auth_Result::SUCCESS:
        	Zend_Registry::get('dt_log')->log('user has been identified using cookie',7);
        	$dt_user = $dt_auth->getIdentity();
    		Zend_Registry::set('dt_user', $dt_user);
        	break;

    	default:
        break;
		}
		
  	}
  	
  	//If the module is admin, we add an additional CSS
  	if(Zend_Controller_Front::getInstance()->getRequest()->getModuleName() == 'admin') {
	  	$view = Zend_Layout::getMvcInstance()->getView();
	  	$view->headLink()->appendStylesheet($view->ressourcesBaseUrl().'/style/futurvert/admin.css');
  	}
  	
 */   	
  } //end predispatch

  public function postDispatch(Zend_Controller_Request_Abstract $request) {  	
  	
  	
  } 


  protected function _initConfig() {

	//we are trying to load the conf, may not work if ENVIRONMENT badly set
	//No need to catch the error has this is mandatory stuff	//$dt_AppConfig = new Zend_Config_Xml('config/main.xml', 'production',true);

	$draftrack_appConfig = new Zend_Config_Ini('config/config.ini', 'production',true);





	//We check if some additional configuration need to be plugged in the configuration
	//This can be usefull for regression purpose where we will need some precise settings for the tests
	//The file must be called local and be set in the config folder
	//the XMl must also start with <local>
/*
	if(is_file(APPLICATION_PATH.'/config/config_local.ini')) {
		$appConfig_local = new Zend_Config_Ini('config/config_local.ini', 'local');
		$appConfig->merge($dt_AppConfig_local);
		Zend_Controller_Front::getInstance()->setParam('env', 'local');
	}


	//We check if some passwords are not defined in the secret.ini file
	if(is_file(APPLICATION_PATH.'/config/secret.ini')) {
		$appConfig_secret = new Zend_Config_Ini('config/secret.ini', 'secret');
		$appConfig->merge($dt_AppConfig_secret);
	}
*/
	//No more update allowed on the config after this point
	$draftrack_appConfig->setReadOnly();


	//First, we check if we can display the app or if the app is under maintenance and cannot be displayed
/*
	if($draftrack_appConfig->master_switch->take_offline == true)
	{
		//we send an header 503 to tell the client that the app is under maintenance
		header("HTTP/1.1 503 Service Unavailable");
		echo 'Sorry the application is not available while we are doing voodoo things';
		exit;	
	}	
*/
	
	//set the error reporting, should be turned off for production setting none
	if($draftrack_appConfig->phpErrorReport == 'all') {
		error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
		ini_set("display_errors", 1);
		ini_set('display_startup_errors', 1);
	}
	else if($draftrack_appConfig->phpErrorReport == 'none') {
		error_reporting(0);
		ini_set("display_errors", 0);
		ini_set('display_startup_errors', 0);
	}
	//Prefer setting by default to the stricter one
	else {
		error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
		ini_set("display_errors", 1);
		ini_set('display_startup_errors', 1);
	}

	//We register it so we are sure it is available everywhere
	//Now we have the registry, we can register our config file for global access 
	Zend_Registry::set('draftrack_appConfig', $draftrack_appConfig);
		
	//You may require some additional ini configuration, this little help can save the day
	//Set it in the format <iniName>newValue</iniName> under <ini_set>
/*
	if(isset($dt_AppConfig->ini_set) && !empty($dt_AppConfig->ini_set)) {
		foreach($dt_AppConfig->ini_set as $name => $value) {
			$iniName= preg_replace('/@/', '.', $name);

			ini_set($iniName,$value);
			
		}
	}
*/	

  }

  protected function _initLog() {
 /* 	
	$dt_appLog = new Zend_Log();
	//We can t log until the end that somthing did not work
	$dt_logCreationIssueOccured = false;
	$dt_AppConfig = Zend_Registry::get('dt_AppConfig');
	
	//logs are disabled so we set a null writer so all the logs are sent to nowhere
	if($dt_AppConfig->log->enable == false) 
	{
		$dt_nullWriter = new Zend_Log_Writer_Null;
		$dt_appLog->addWriter($dt_nullWriter);
	}	
	else 
	{
		//user requests logs to be sent to a log file 
		if( isset($dt_AppConfig->log->text_log) && isset($dt_AppConfig->log->text_log->log_stream) ) {
			//we check that the log destination is writable
				try {    			//We create the writer
    			$dt_textWriter = new Zend_Log_Writer_Stream($dt_AppConfig->log->text_log->log_stream);
				
				//We check if a particular filter needs to be applied
				if( isset($dt_AppConfig->log->text_log->filter_priority) && is_numeric($dt_AppConfig->log->text_log->filter_priority) ) {
					$dt_filterPriority = (int) $dt_AppConfig->log->text_log->filter_priority;
					$dt_textFilter = new Zend_Log_Filter_Priority($dt_filterPriority);	
					$dt_textWriter->addFilter($dt_textFilter);
				}
				//We add the writer to the logs
				$dt_appLog->addWriter($dt_textWriter);
				
				} 	catch (exception $e) {
					//We just add a log at the end to say that somethng did not work
					$dt_logCreationIssueOccured = true;
				}
			}//end text_log writer
	
		//user wants to send the logs to firebug (check http://framework.zend.com/manual/en/zend.log.writers.html#zend.log.writers.firebug for details)
		if(isset($dt_AppConfig->log->firebug_log->enable) && $dt_AppConfig->log->firebug_log->enable == true) {
			
				try {
				$dt_firebugWriter = new Zend_Log_Writer_Firebug();
			
				//We check if a particular filter needs to be applied
				if( isset($dt_AppConfig->log->firebug_log->filter_priority) && is_numeric($dt_AppConfig->log->firebug_log->filter_priority) ) {
					$dt_filterPriority = (int) $dt_AppConfig->log->firebug_log->filter_priority;
					$dt_textFilter = new Zend_Log_Filter_Priority($dt_filterPriority);	
					$dt_firebugWriter->addFilter($dt_textFilter);
				}
			
				//We add the writer to the logs
				$dt_appLog->addWriter($dt_firebugWriter);
				
				} 	catch (exception $e) {
					$dt_logCreationIssueOccured = true;			
				}
		} //end firebug logging
	} //end log writer creation


	//Check if there is at least one writer that succeeded, if not we create a mock one
	try {
		$dt_appLog->log('Check that writters are available', Zend_Log::DEBUG);
	} catch (exception $e) {
		//No writter is available, we create a mock one
		$dt_nullWriter = new Zend_Log_Writer_Null;
		$dt_appLog->addWriter($dt_nullWriter);
	}

	//If an issue occured on one of the writers, we log it
	if($dt_logCreationIssueOccured) {
		$dt_appLog->log('An issue occured while creating the different logs, you should have a look at the log initialisation', Zend_Log::ERR);	
	}

	//We set them as global variables to be accessible inside classes
	Zend_Registry::set('dt_log', $dt_appLog);
  	
  	//We check if the executiontime need to be logged
  	$execTime = Zend_ExecutionTime::getInstance();
  	try {
  		$execTime->setConfig($dt_AppConfig->log_long_queries);
  	} catch (exception $e) {
  		$dt_appLog->log($e->getMessage(), Zend_Log::ERR);	
  	}
*/  	
  } //end _initLog
  
  
  
  
	protected function _initDb() {
 /* 	
	$dt_AppConfig = Zend_Registry::get('dt_AppConfig');
	$dt_appLog = Zend_Registry::get('dt_log');
	
	////////////////We initiate the different databases that will be used by the application   //////////////////////////////
	if(!is_file(APPLICATION_PATH.'/'.$dt_AppConfig->database_configuration)) {

         require_once 'Zend/Db/Exception.php';
		throw new Zend_Db_Exception('db configuration file missing');	

	}

	$environment = Zend_Controller_Front::getInstance()->getParam('env');
	$dt_dbConfig = new Zend_Config_Ini($dt_AppConfig->database_configuration, $environment);

	//This is the manager when the different plugin may require the db link to be used
	require_once('src/Zend_extension/Db/dbManager.php');

	try {
		$dt_databases  = new dbManager($dt_dbConfig->databases);
	} catch (exception $e) {
		require_once 'Zend/Db/Exception.php';
		throw new Zend_Db_Exception('Issue occured while creating dbManager: '. $e->getMessage().'. Please check db configuration file');	
	}
	


	//We set the db manager as global soit can be accessed from within classes
	Zend_Registry::set('dt_databases', $dt_databases);

	////////////////Dbs are initiated ///////////////////////////////////////////////////////////////////////////////////////

	/////////// check if we should profile database queries ///////////////////////////
	if(isset($dt_AppConfig->profiler->enable) && $dt_AppConfig->profiler->enable == true) {

		if($dt_AppConfig->profiler->where == 'firebug') {
			$dt_profiler = new Zend_Db_Profiler_Firebug();
		}
		elseif($dt_AppConfig->profiler->where == 'stream') {
		
			require_once('src/Zend_extension/Db/Profiler/stream.php');
			try{ 
				$dt_profiler = new Zend_Db_Profiler_Stream($dt_AppConfig->profiler);
			} catch (exception $e) {
				$dt_appLog->log('Issue opening profile stream: '. $e->getMessage().'. Please check profile configuration ', Zend_Log::ERR);	
			}
		}	
	
		if(isset($dt_profiler)) {
			$dt_profiler->setEnabled(true);
			// Attach the profiler to your db adapter
			$dt_databases->setProfiler($dt_profiler);
		}
	} //end initDbprofiling

*/

  	} //end _initDb

	protected function _initSession() {
/*
		$dt_AppConfig = Zend_Registry::get('dt_AppConfig');
		$dt_databases = Zend_Registry::get('dt_databases');
		
		if($dt_AppConfig->session->use_database == true) {
			require_once 'Zend/session/SaveHandler/DbTable.php';
			//get your database connection ready
			$dt_sessionDb =  $dt_databases->selectDb('session');
		
			//creation of the table 
			//$dt_sessionDb->query('CREATE TABLE `session` (`id` char(32),`modified` int,`lifetime` int,`data` text,PRIMARY KEY (`id`))');

			Zend_Db_Table_Abstract::setDefaultAdapter($dt_sessionDb);
			$config = array(
    			'name'           => 'session',
    			'primary'        => 'id',
    			'modifiedColumn' => 'modified',
    			'dataColumn'     => 'data',
    			'lifetimeColumn' => 'lifetime'
			);

			//create your Zend_Session_SaveHandler_DbTable and
			//set the save handler for Zend_Session
			Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
		}


		//start your session!
		if(!empty($dt_AppConfig->session->config)) {	
			Zend_Session::setOptions($dt_AppConfig->session->config->toArray());
		}
		require_once('src/Zend_extension/Auth/User.php');
		Zend_Session::start();
	//now you can use Zend_Session like any other time	

*/
	} //end _initSession
	
	
	protected function _initLayout(){

/*
		Zend_Layout::startMvc(array('layoutPath' => APPLICATION_PATH .'/src/layouts','layout' =>'futurvert'));
		$view = Zend_Layout::getMvcInstance()->getView();
		$view->addBasePath(APPLICATION_PATH .'/src/views','Zend_View');
		$view->setEncoding('UTF-8');
		$view->doctype('XHTML1_TRANSITIONAL');
		$view->headMeta()->appendHttpEquiv('Content-Type','text/html; charset=UTF-8');
		$view->headLink()->appendStylesheet($view->ressourcesBaseUrl().'/style/futurvert/style.css');
		$view->headScript()->appendFile('http://yui.yahooapis.com/2.7.0/build/yuiloader/yuiloader-min.js', 'text/javascript');
		unset($view);

*/
	}


} // end initialization helper

?>